package com.wangdong.yating.okhttp3;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;


import com.wangdong.yating.R;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 作者：wangdong on 2018/8/31 12:00
 * 邮箱：2100520956@qq.com
 *
 * 处理https
 * 测试自己签名的https
 *
 * 那么本篇博文的基本内容包含：

                https一些相关的知识
                okhttp访问自签名https网站
                如何构建一个支持https的服务器（这里主要为了测试多个证书的时候，如何去加载）
                如何进行双向证书验证
 *   HTTPS相当于HTTP的安全版本，为什么安全呢？
 *          因为它在HTTP的之下加入了SSL (Secure Socket Layer)，安全的基础就靠这个SSL了。SSL位于TCP/IP和HTTP协议之间，那么它到底能干嘛呢？

            它能够：

            认证用户和服务器，确保数据发送到正确的客户机和服务器；(验证证书)
            加密数据以防止数据中途被窃取；（加密）
            维护数据的完整性，确保数据在传输过程中不被改变。（摘要算法）
 *
 *
 *
 *
 */

public class OKHttpsSLLActivity extends AppCompatActivity
{

    private OkHttpClient okHttpClient;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_okhttps_sll);
        okHttpClient = new OkHttpClient();
    }


    /**
     * 本来想测试12306 网站不安全的https 是自己的 签名但是 没想到现在12306 也是CA机构颁发
     *          所以没有报错
     *          if 是自己的签名https 访问时候会报错
     *          会爆出如下错误

     javax.net.ssl.SSLHandshakeException:
     java.security.cert.CertPathValidatorException:
     Trust anchor for certification path not found.
     * */
    public void getHttps(View view) {

        Request request =new Request.Builder()
                .url("https://kyfw.12306.cn/otn/")
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(OKHttpsSLLActivity.this,
                        "访问失败", Toast.LENGTH_SHORT).show();
                e.printStackTrace();


            }

            @Override
            public void onResponse(Call call, Response response)
                    throws IOException {
                Log.i("wangdong",response.body().string());

            }
        });

    }


    /**详情https查看网址
     * https://blog.csdn.net/lmj623565791/article/details/48129405*/
    public void setCertificates(InputStream... certificates)
    {
        try
        {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            int index = 0;
            for (InputStream certificate : certificates)
            {
                String certificateAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));

                try
                {
                    if (certificate != null)
                        certificate.close();
                } catch (IOException e)
                {
                }
            }

            SSLContext sslContext = SSLContext.getInstance("TLS");

            TrustManagerFactory trustManagerFactory =
                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

            trustManagerFactory.init(keyStore);
            sslContext.init
                    (
                            null,
                            trustManagerFactory.getTrustManagers(),
                            new SecureRandom()
                    );
//            okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());


        } catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}
